﻿using NAudio.Wave;
using NAudio.Lame;
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DLAudioChat
{
    static class Program
    {

        private static WaveInEvent waveIn;
        private static WaveFileWriter waveWriter;
        private static readonly string outputFilePath = "C:\\Users\\DL\\Desktop\\zhuomianhaoluan\\DLAudioChat (3) (2)\\output\\output.wav";
        private static readonly string mp3outputFilePath = "C:\\Users\\DL\\Desktop\\zhuomianhaoluan\\DLAudioChat (3) (2)\\output\\outputmp3.mp3";
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // 开始录音
            StartRecording();

            // 注册窗口关闭事件
            Application.ApplicationExit += new EventHandler(ApplicationExitHandler);

            Application.Run(new Form1());
        }

        private static void StartRecording()
        {
            // 创建WaveInEvent实例
            waveIn = new WaveInEvent();
            waveIn.WaveFormat = new WaveFormat(44100, 1);

            // 创建WaveFileWriter实例
            waveWriter = new WaveFileWriter(outputFilePath, waveIn.WaveFormat);

            // 注册数据接收事件
            waveIn.DataAvailable += new EventHandler<WaveInEventArgs>(DataAvailableHandler);

            // 开始录音
            waveIn.StartRecording();
        }

        private static void StopRecording()
        {
             // 停止录音
            waveIn.StopRecording();
            waveIn.Dispose();
            waveIn = null;

            // 关闭WaveFileWriter
            waveWriter.Close();
            waveWriter.Dispose();
            waveWriter = null;

        }

        private static void DataAvailableHandler(object sender, WaveInEventArgs e)
        {
            // 写入录音数据
            waveWriter.Write(e.Buffer, 0, e.BytesRecorded);
        }

        private static void ApplicationExitHandler(object sender, EventArgs e)
        {
            // 停止录音
            StopRecording();
            // 将录音文件转换为MP3格式
            ConvertWavToMp3(outputFilePath, mp3outputFilePath);
        }
        private static void ConvertWavToMp3(string wavFilePath, string mp3FilePath)
        {
            using (var reader = new AudioFileReader(wavFilePath))
            {
                using (var writer = new LameMP3FileWriter(mp3FilePath, reader.WaveFormat, 128))
                {
                    reader.CopyTo(writer);
                }
            }
        }

    }
}
